<template>
<div class="gs-geocoder">
  <div :class="$style.top">
    <div :class="$style.row">
      <!-- <label>*地区:</label> -->
      <el-select
        ref="select"
        :value="address"
        :clearable="true"
        :class="$style.select"
        @clear="onClear"
        placeholder="请选择地区"
        @visible-change="onVisible"
      >
        <Tabs
          slot="empty"
          :active.sync="active"
          :tab-list="tabList"
          @check="onCheck"
        />
      </el-select>
    </div>
    <div :class="$style.row">
      <!-- <label>*详细地址:</label> -->
      <el-autocomplete
        ref="autocomplete"
        v-model="keyword"
        :class="$style.keyword"
        :popper-class="$style.autocomplete"
        :fetch-suggestions="onSuggestion"
        placeholder="请输入详细地址"
        :trigger-on-focus="false"
        select-when-unmatched
        :debounce="500"
        @select="onSelect"
        @keyup.enter.native="onEnter"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="onEnter"
        />
        <template slot-scope="{ item }">
          <p :class="$style.name">
            {{ item.value }}
          </p>
          <span :class="$style.addr">{{ item.address }}</span>
        </template>
      </el-autocomplete>
    </div>
    <p :class="$style.row">
      <!-- <label>经纬度:</label> -->
      <el-input
        :value="lnglat"
        readonly=""
        placeholder="请选择地图中的经纬度"
        :class="$style.noborder"
      />
      <el-button @click="open" v-show="type==='2'">{{openMap}}</el-button>
      <el-button @click="open" v-show="type==='1'">{{openMap}}</el-button>
    </p>
  </div>
  <!-- {{ distracts }} -->

  <div :class="$style.main" v-show="type==='1'">
    <Amap
      :mkey="mkey"
      :center="center"
      :position.sync="position"
      :zoom.sync="size"
      :region="region"
      :place-searcher.sync="placeSearcher"
      :district-searcher.sync="districtSearcher"
      :boundaries="boundaries"
    />
  </div>
</div>
</template>

<script>
import Tabs from './tabs';
import Amap from './amap.vue';

export default {
  components: {
    Tabs,
    Amap,
  },
  props: {
    city: {
      type: String,
      default: '110000',
    },
    mapkey: {
      type: String,
      default: '34baeeffef935b3053ea90d373c91f73',
      // default: 'f60c4af17eea56eac3a0d459463ec0c8',
      // required: true,
    },
    zoom: {
      type: Number,
      default: 10,
    },
    gicValue: {
      type: Object,
      default(){
        return {
          province: '',
          city: '',
          area: '',
          street: '',
          address: '',
          longitude: '',
          latitude: '',
          type: ''
        }
      }
    }
  },
  data() {
    return {
      maps:false,
      type:'2',
      openMap:'打开地图',
      active: '0',                // tabs组件当前位置
      distracts: [this.gicValue.province, this.gicValue.city, this.gicValue.area, this.gicValue.street], // 省市县下拉框数值
      keyword: this.gicValue.address,                // 详细地址
      center: this.city,          // 地图中心点坐标 默认北京
      position: '',               // 坐标位置
      mkey: this.mapkey,          // 高德 jsAPI 地图 key
      region: this.city,          // 搜索建议城市
      // msg: '',                    // 搜索地址错误信息
      size: this.zoom,            // 地图缩放等级
      placeSearcher: null,
      districtSearcher: null,
      tabList: [[], [], [], []],  // tab组件内部数据
      boundaries: [],             // 行政区轮廓数据
    };
  },
  computed: {
    address(){
      const list = this.distracts.filter(x => x);
      this.$emit('changeGic','address',list)
      return list.join('/');
    },
    lnglat(){
      const { position } = this;
      if (position && position.lng){
        const { lng, lat } = position;
        this.$emit('changeGic','lng',lng)
        this.$emit('changeGic','lat',lat)
        return lng +','+ lat;
      }
      this.$emit('changeGic','lng','')
      this.$emit('changeGic','lat','')
      return '';
    },
  },
  watch: {
    gicValue: {
      deep: true,
      immediate: true,
      handler: function (newValue,oldValue) {
        this.distracts = [this.gicValue.province, this.gicValue.city, this.gicValue.area, this.gicValue.street]
        this.keyword = this.gicValue.address
        this.type = this.gicValue.type?this.gicValue.type:'1'
        if(this.type==='2'){
          this.openMap = '打开地图'
        }else{
          this.openMap = '关闭地图'
        }
        if(this.gicValue.latitude){
          this.$set(this,'position',{ lat: this.gicValue.latitude, lng: this.gicValue.longitude })
        }
      }
    },
    districtSearcher(){
      this.getDistricts(0, '100000');        // 当区域检索器好了,就加载一次
    },
    keyword(){
      this.$emit('changeGic','keyword',this.keyword)
    },
  },
  mounted() {
    if(this.gicValue.latitude){
      this.$set(this,'position',{ lat: this.gicValue.latitude, lng: this.gicValue.longitude })
    }
  },
  methods: {
    getParams(ops){
      let url = '';
      // 传入预览参数
      for (const a in ops) {
        const v = encodeURIComponent(ops[a]);
        url += '&'+a+'='+v;
      }
      return url;
    },
    open(){
      if(this.type==='2'){
        this.type = '1';
        this.openMap = '关闭地图'
      }else{
        this.type = '2';
        this.openMap = '打开地图'
      }
    },
    clearVal(){
      this.active = '0';
      this.distracts = ['', '', '', ''];
      this.type = '1'
      this.$set(this,'position',{ lat: '', lng: ''})
      // this.$set(this,'position',{ lat: '', lng: ''})
      // this.lnglat = null
      this.keyword = ''
      // console.log('11111111')

    },
    // 切换省市县标签
    onCheck(item) {
      console.log(item,22222)
      const { tabList, distracts } = this;
      const { adcode, idx, name, level, center } = item;
      // 重选清空老数据
      const nDis = distracts.map((x, i) => {
        if (i < idx) {
          return x;
        }
        if (i === idx) {
          return name;
        }
        return '';
      });
      this.distracts = nDis;
      if (idx < 2){
        this.region = adcode;
      }
      if (idx < 3){
        const active = idx + 1+'';
        const nList = tabList.map((x, i) => (i <= idx) ? x : []);
        console.log(nList,666)
        this.tabList = nList;
        this.active = active;
        this.getDistricts(active, adcode, level);
      } else {
        this.$refs.select.blur();
        this.size = 14;
        this.center = center;
      }
    },
    onClear(){
      this.active = '0';
      this.distracts = ['', '', '', ''];
    },
    onVisible(val){

    },
    onSelect(item){
      const { location } = item;
      if (location){
        this.position = location;
        // this.onReverse(location);
      }
    },
    onSuggestion(keyword, cb){
      const { placeSearcher, region, distracts } = this;
      // 只能搜索城市级, 所以 区 和 街道 要变为搜索条件
      const [,, c, d] = distracts;
      const address = c + d + keyword;
      placeSearcher.setCity(region);
      placeSearcher.search(address, (status, data) => {
        if (data.poiList){
          const { pois } = data.poiList;
          const list = pois.map(x => {
            const { address, name: value, location: loc } = x;
            const { lng, lat } = loc;
            const location = { lng, lat };
            return { address, value, location };
          });
          return cb(list);
        }
        this.$message({
          message: '未搜索到具体地址...',
          type: 'warning',
        });
        cb([]);
      });
    },
    onEnter(){
      this.$refs.autocomplete.close();
    },
    getDistricts(idx, adcode, level) {
      const { districtSearcher, tabList, $set } = this;
      if (level){
        districtSearcher.setLevel(level);           // 重置行政区级别
        districtSearcher.setExtensions('all');
      }
      districtSearcher.search(adcode, (status, data) => {
        const { districtList, boundaries } = data.districtList[0];
        $set(tabList, idx, districtList);
        this.boundaries = boundaries;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
  
</style>
<style lang="less" module>
:global{
  .gs-geocoder{
    height: 600px;
    margin: 0 auto;
  }
}

.row{
  display: flex;
  margin: 10px 0;
  &>label{
    display: flex;
    width: 80px;
    justify-content: end;
    align-items: center;
    padding: 0 1em 0 0;
  }
}
.top{
  font-size: 14px;
}
.select, .keyword{
  width: 100%;
}
.autocomplete{
  li {
    line-height: normal;
    padding: 7px 20px;
  }
}
.name {
  margin: 0;
  text-overflow: ellipsis;
  overflow: hidden;
}
.addr {
  font-size: 12px;
  color: #b4b4b4;
}
.noborder{
  input{
    // border: none;
    // border-bottom: 2px solid #b4b4b4;
    // border-radius: 0;
    // padding: 0;
    // text-align: center;
  }
}
.main{
  border: 1px solid #d7dae2;
  border-radius: 2px;
  height: calc(100% - 120px);
}
</style>
